package com.github.postsanf.yinian.activity;

import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.github.postsanf.yinian.BaseActivity;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.bean.YNVideoInfo;
import com.github.postsanf.yinian.constants.ACTIONs;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.constants.SelectedImg;
import com.github.postsanf.yinian.entity.YNUpTokenResponse;
import com.github.postsanf.yinian.service.UpLoadService;
import com.github.postsanf.yinian.utils.ReqUtils;
import com.github.postsanf.yinian.utils.SizeFormat;
import com.github.postsanf.yinian.utils.StringUtils;
import com.github.postsanf.yinian.utils.SystemUtils;
import com.github.postsanf.yinian.utils.UIHelper;
import com.litesuits.http.exception.HttpException;
import com.litesuits.http.listener.HttpListener;
import com.litesuits.http.request.StringRequest;
import com.litesuits.http.request.param.HttpMethods;
import com.litesuits.http.response.Response;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UpProgressHandler;
import com.qiniu.android.storage.UploadManager;
import com.qiniu.android.storage.UploadOptions;
import com.umeng.analytics.MobclickAgent;
import com.umeng.socialize.utils.Log;

import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

public class VideoLocalEditActivity extends BaseActivity implements View.OnClickListener {
    private EditText et_imagelocaledit;
    private ImageView iv_back;
    private TextView imagelocal_send;
    private TextView imagelocal_ed_sure;
    private ImageButton imagelocal_edit_cover;
    private ImageView video_edit_pic;
    private TextView video_edit_time;
    private ProgressDialog mProgressDialog;
    private ConnectivityManager mConnectivityManager;
    private String fsize;
    SharedPreferences.Editor editor;
    private YNVideoInfo ynVideoInfo;
    private Bitmap VideothumbBitmap;
    private String VideothumbTime;
    private UploadManager mUpManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.yn_videolocal_edit);
        mUpManager = application.getUploadManager();
        registerBoradcastReceiver();
        mConnectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        editor = getSharedPreferences(ACTIONs.mynetwork, 0).edit();
        initView();
    }

    private void initView() {
        iv_back = (ImageView) findViewById(R.id.iv_back);
        findViewById(R.id.rl_pop_top).setOnClickListener(this);
        findViewById(R.id.word_kit).setOnClickListener(this);
        imagelocal_send = (TextView) findViewById(R.id.imagelocal_send);
        imagelocal_ed_sure = (TextView) findViewById(R.id.imagelocal_ed_sure);
        iv_back.setOnClickListener(this);
        imagelocal_send.setOnClickListener(this);
        imagelocal_ed_sure.setOnClickListener(this);
        et_imagelocaledit = (EditText) findViewById(R.id.et_imagelocaledit);
        et_imagelocaledit.clearFocus();
        et_imagelocaledit.setCursorVisible(false);
        imagelocal_edit_cover = (ImageButton) findViewById(R.id.imagelocal_edit_cover);
        imagelocal_edit_cover.setOnClickListener(this);
        video_edit_pic = (ImageView) findViewById(R.id.video_edit_pic);
        video_edit_time = (TextView) findViewById(R.id.video_edit_time);
        if (SelectedImg.mSelectedVideo.size() > 0) {
            ynVideoInfo = SelectedImg.mSelectedVideo.get(0);
            VideothumbBitmap = UIHelper.getVideoThumbnail(ynVideoInfo.getPath());
            video_edit_pic.setImageBitmap(VideothumbBitmap);
            VideothumbTime = new SimpleDateFormat("mm:ss").format(new Date(ynVideoInfo.getDuration()));
            video_edit_time.setText(VideothumbTime);
            video_edit_pic.setOnClickListener(this);
        }

    }


    public boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击的是输入框区域，保留点击EditText的事件
                et_imagelocaledit.setCursorVisible(true);
                imagelocal_edit_cover.setVisibility(View.VISIBLE);
                iv_back.setVisibility(View.GONE);
                imagelocal_send.setVisibility(View.GONE);
                imagelocal_ed_sure.setVisibility(View.VISIBLE);
                return false;
            } else {
                et_imagelocaledit.setCursorVisible(false);
                return true;
            }
        }
        return false;
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        // 必不可少，否则所有的组件都不会有TouchEvent了
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }


    private ProgressDialog pd;

    Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                if (pd != null)
                    pd.dismiss();
                if (mConnectivityManager.getActiveNetworkInfo() != null && mConnectivityManager.getActiveNetworkInfo().isAvailable()) {
                    if (mConnectivityManager.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_WIFI) {
                        //WiFi网络
                        doUpImg(false);
                    } else if (mConnectivityManager.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_MOBILE) {
                        //3g网络
                        int netfrist = getSharedPreferences(ACTIONs.mynetwork, 0).getInt(ACTIONs.networkFrist, 0);
                        String nettype = getSharedPreferences(ACTIONs.mynetwork, 0).getString(ACTIONs.networkType, "");
                        if (!nettype.equals("") && nettype.equals(ACTIONs.network3GWIFI)) {
                            doUpImg(false);
                        } else {
                            if (netfrist == 0) {
                                FristNetWork(fsize);
                                editor.putInt(ACTIONs.networkFrist, 1);
                                editor.commit();
                            } else {
                                SecondNetWork(fsize);
                            }
                        }
                    }
                } else {
                    if (pd != null)
                        pd.dismiss();
                }
            }
        }
    };

    public void FristNetWork(String fsize) {
        final AlertDialog dlg = new AlertDialog.Builder(this).create();
        dlg.show();
        Window window = dlg.getWindow();
        window.setContentView(R.layout.publish_network_dialog);
        TextView tt = (TextView) window.findViewById(R.id.pp_title);
        tt.setText("您现在处于移动网络环境下，将消耗" + fsize + "流量，是否使用流量继续上传?");
        final TextView ok = (TextView) window.findViewById(R.id.btn_ep_ok);
        ok.setText("不允许");
        ok.setBackgroundColor(getResources().getColor(R.color.white));
        ok.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                doUpImg(true);
                dlg.cancel();
            }
        });
        final TextView cancel = (TextView) window
                .findViewById(R.id.btn_ep_cancel);
        cancel.setText("确定");
        cancel.setBackgroundColor(getResources().getColor(R.color.white));
        cancel.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                editor.putString(ACTIONs.networkType, ACTIONs.network3GWIFI);
                editor.commit();
                doUpImg(false);
                dlg.cancel();
            }
        });
    }

    public void SecondNetWork(String fsize) {
        final AlertDialog dlg = new AlertDialog.Builder(this).create();
        dlg.show();
        Window window = dlg.getWindow();
        window.setContentView(R.layout.publish_network_dialog);
        TextView tt = (TextView) window.findViewById(R.id.pp_title);
        tt.setText(">_< 您关闭了使用流量上传开关，你在使用3g/4g网络环境下，这会消耗您" + fsize + "流量，确定继续上传吗？");
        final TextView ok = (TextView) window.findViewById(R.id.btn_ep_ok);
        ok.setText("取消");
        ok.setBackgroundColor(getResources().getColor(R.color.white));
        ok.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                dlg.cancel();
            }
        });
        final TextView cancel = (TextView) window
                .findViewById(R.id.btn_ep_cancel);
        cancel.setText("仅一次");
        cancel.setBackgroundColor(getResources().getColor(R.color.white));
        cancel.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                doUpImg(false);
                dlg.cancel();
            }
        });
    }

    private String contentstr;
    private long upstorge;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.word_kit:
                startActivity(new Intent(VideoLocalEditActivity.this, TextEditKitActivity.class));
                break;
            case R.id.imagelocal_send:
                contentstr = et_imagelocaledit.getText().toString();
                long totalSize = 0;
                for (int i = 0; i < SelectedImg.mSelectedImage.size(); i++) {
                    String address = SelectedImg.mSelectedImage.get(i);
                    if (!address.startsWith("http")) {
                        File uploadImg = new File(address);
                        long imgSize = uploadImg.length();
                        totalSize += imgSize;
                    }
                }
                upstorge = totalSize;
                fsize = SizeFormat.formatSize(totalSize);
                getTokenJieTu();
                break;
            case R.id.rl_pop_top:
            case R.id.imagelocal_edit_cover:
            case R.id.imagelocal_ed_sure:
                imagelocal_edit_cover.setVisibility(View.GONE);
                iv_back.setVisibility(View.VISIBLE);
                imagelocal_send.setVisibility(View.VISIBLE);
                imagelocal_ed_sure.setVisibility(View.GONE);
                InputMethodManager imm = (InputMethodManager)
                        getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                break;
            case R.id.video_edit_pic:
                Intent zoomintent = new Intent(VideoLocalEditActivity.this, LocalManageVideoPreviewActivity.class);
                zoomintent.putExtra("localVideopath", ynVideoInfo.getPath());
                startActivity(zoomintent);
                break;
            default:
                break;
        }
    }

    public byte[] Bitmap2Bytes(Bitmap bm) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
        return baos.toByteArray();
    }

    private String videoCoverUrl;

    private void getTokenJieTu() {
        pd = ProgressDialog.show(VideoLocalEditActivity.this, "", "发布中...", false, false);
        StringRequest req = new StringRequest(getString(R.string.BASE_URL) + getString(R.string.ynGetUploadToken))
                .setMethod(HttpMethods.Post)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        YNUpTokenResponse resToken = gson.fromJson(s, YNUpTokenResponse.class);
                        if (ReqUtils.isSuccess(resToken.getCode())) {
                            mUpManager.put(Bitmap2Bytes(VideothumbBitmap), UUID.randomUUID().toString() + ".png", resToken.getData().get(0).getToken(),
                                    new UpCompletionHandler() {
                                        @Override
                                        public void complete(String key, ResponseInfo info, JSONObject res) {
                                        }
                                    }, new UploadOptions(null, null, false, new UpProgressHandler() {
                                        public void progress(String key, double percent) {
                                            if (percent == 1.0) {
                                                videoCoverUrl = "http://7xlmtr.com1.z0.glb.clouddn.com/" + key;
                                                Log.i("xjs", "videoCoverUrl==>" + videoCoverUrl);
                                                if (SelectedImg.mSelectedVideo.size() > 0) {
                                                    mHandler.sendEmptyMessage(1);
                                                }
                                            }
                                        }
                                    }, null));
                        } else {
                            showToast(resToken.getMsg());
                            pd.dismiss();
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        pd.dismiss();
                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }

    private void doUpImg(boolean isPause) {
        mProgressDialog = ProgressDialog.show(this, "", CommonConstants.TIP_LOAD_UP);
        Intent mIntent = new Intent(this, UpLoadService.class);
        mIntent.setAction(ACTIONs.actionPublishVideo);
        mIntent.putExtra(ACTIONs.aUid, application.getCurID() + "");
        mIntent.putExtra(ACTIONs.aGid, application.getCurGid() + "");
        mIntent.putExtra(ACTIONs.aContent, contentstr);
        mIntent.putExtra(ACTIONs.upstorage, SizeFormat.formatDouble(upstorge, SizeFormat.FZ_KB));
        mIntent.putExtra(ACTIONs.upcover, videoCoverUrl);
        mIntent.putExtra(ACTIONs.uptime, VideothumbTime);
        mIntent.putExtra(ACTIONs.aisPause, isPause);
        mIntent.putExtra(ACTIONs.upsource, SystemUtils.getAppStoreName(VideoLocalEditActivity.this, "UMENG_CHANNEL"));
        startService(mIntent);
        startActivity(new Intent(this, UpLoadActivity.class).putExtra(ACTIONs.IstoSetWifi, isPause));
        Intent upIntent = new Intent(ACTIONs.actionCloseAlbum);
        upIntent.putExtra(ACTIONs.aIsClearSelect, 1);
        sendBroadcast(upIntent);
        mProgressDialog.dismiss();
        finish();
    }


    private void registerBoradcastReceiver() {
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction("kitContent");
        this.registerReceiver(mBroadcastReceiver, myIntentFilter);
    }


    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {
                case "kitContent":
                    String ettext = et_imagelocaledit.getText().toString();
                    String text = intent.getStringExtra("text");
                    if (StringUtils.isEmpty(ettext)) {
                        et_imagelocaledit.setText(text);
                    } else {
                        et_imagelocaledit.setText(ettext + "\n" + text);
                    }
                    break;
            }
        }
    };


    @Override
    public void onBackPressed() {
        super.onBackPressed();

    }


    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(this.getClass().getSimpleName());
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(this.getClass().getSimpleName());
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        this.unregisterReceiver(mBroadcastReceiver);
    }

}
